<template>
  <div id="app">
    <el-container>
      <el-header>
        <el-menu :default-active="activeIndex"
                 mode="horizontal"
                 style="justify-content: center;" @select="handleSelect">
          <el-menu-item index="simple">普通验证码</el-menu-item>
          <el-menu-item index="behavior">行为验证码</el-menu-item>
        </el-menu>
      </el-header>
      <el-main>
        <el-card v-if="activeIndex === 'simple'">
          <el-button-group style="margin-bottom: 10px">
            <el-button type="primary" @click="changeSimpleImageType('spec')">常规</el-button>
            <el-button type="primary" @click="changeSimpleImageType('gif')">gif</el-button>
            <el-button type="primary" @click="changeSimpleImageType('chinese')">中文</el-button>
            <el-button type="primary" @click="changeSimpleImageType('chinese_gif')">中文gif</el-button>
            <el-button type="primary" @click="changeSimpleImageType('arithmetic')">简单算术</el-button>
          </el-button-group>
          <el-form :model="simpleImageForm" inline>
            <el-form-item prop="code">
              <el-input v-model="simpleImageForm.code" placeholder="请输入验证码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-image :src="simpleImageUrl"></el-image>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="refreshSimpleImage">刷新</el-button>
              <el-button type="primary" @click="verifySimpleImage">验证</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-if="activeIndex === 'behavior'">
          <el-button-group style="margin-bottom: 10px">
            <el-button :disabled="loading" type="primary"
                       @click="changeBehaviorImageType(BEHAVIOR_TYPES[Math.floor(Math.random() * BEHAVIOR_TYPES.length)])">
              随机
            </el-button>
            <el-button :disabled="loading" type="primary" @click="changeBehaviorImageType('SLIDER')">滑块验证
            </el-button>
            <el-button :disabled="loading" type="primary" @click="changeBehaviorImageType('ROTATE')">旋转验证
            </el-button>
            <el-button :disabled="loading" type="primary" @click="changeBehaviorImageType('CONCAT')">滑动还原
            </el-button>
            <el-button :disabled="loading" type="primary" @click="changeBehaviorImageType('WORD_IMAGE_CLICK')">文字点选
            </el-button>
          </el-button-group>
          <el-form inline size="small">
            <el-form-item label="语言" label-width="80">
              <el-select v-model="selectLang">
                <el-option v-for="item in langList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="主题" label-width="80">
              <el-select v-model="selectTheme">
                <el-option v-for="item in themeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div style="display: flex;align-items: center;justify-content: center;">
            <kite-config-provider :locale="selectLang" :theme="selectTheme">
              <kite-captcha ref="captchaRef" v-model="matchingResultCode"
                            :render-data-api="renderDataApi"
                            :scale="1"
                            :show-close="true"
                            background-image="https://picsum.photos/1920/1080"
                            @matching-data="handleMatchingData"
                            @render-success="handleRenderSuccess">
              </kite-captcha>
            </kite-config-provider>
          </div>
        </el-card>
      </el-main>
      <el-footer>
        <el-link href="#" type="primary">Kite Captcha</el-link>
      </el-footer>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import qs from 'qs'
import axios from 'axios'
import autofit from "autofit.js"

const BEHAVIOR_TYPES = ['SLIDER', 'CONCAT', 'WORD_IMAGE_CLICK'];
const behaviorType = ref('SLIDER')
const matchingResultCode = ref('')
const selectLang = ref('zh_cn')
const selectTheme = ref('light')

const langList: any[] = [
  {
    label: '简体中文',
    value: 'zh_cn'
  },
  {
    label: '繁体中文',
    value: 'zh_tw'
  },
  {
    label: '英文',
    value: 'en'
  },
  {
    label: '日语',
    value: 'ja'
  },
  {
    label: '韩语',
    value: 'ko'
  }
]

const themeList: any[] = [
  {
    label: '默认',
    value: 'light'
  },
  {
    label: '暗黑',
    value: 'dark'
  }
]

// 定义类型
interface SimpleImageForm {
  code: string
  type: string
  timestamp: string
}

// 响应式数据
const activeIndex = ref('simple')
const simpleImageType = ref('SLIDER')
const simpleImageGenUrl = 'http://localhost:8088/captcha/simple/gen?type='
const simpleImageCheckUrl = 'http://localhost:8088/captcha/simple/check'
const behaviorImageGenUrl = 'http://localhost:8088/captcha/behavior/gen'
const behaviorImageCheckUrl = 'http://localhost:8088/captcha/behavior/check'
const simpleImageUrl = ref('')
const loading = ref(false)
const captchaRef = ref(null)

const simpleImageForm = reactive<SimpleImageForm>({
  code: '',
  type: '',
  timestamp: ''
})


const handleSelect = (key: string) => {
  activeIndex.value = key
}

const changeSimpleImageType = (type: string) => {
  simpleImageType.value = type
  simpleImageForm.timestamp = new Date().getTime().toString()
  simpleImageUrl.value = simpleImageGenUrl + simpleImageType.value + "&timestamp=" + simpleImageForm.timestamp
}

const refreshSimpleImage = () => {
  simpleImageForm.timestamp = new Date().getTime().toString()
  simpleImageForm.code = ''
  simpleImageUrl.value = simpleImageGenUrl + simpleImageType.value + "&timestamp=" + simpleImageForm.timestamp
}

const verifySimpleImage = () => {
  simpleImageForm.type = simpleImageType.value
  if (!simpleImageForm.code) {
    ElMessage.error("请输入验证码")
    return
  }

  axios.post(simpleImageCheckUrl, qs.stringify(simpleImageForm)).then((res: any) => {
    if (res.data.code === 200) {
      ElMessage.success("验证成功")
    } else {
      simpleImageForm.code = ''
      ElMessage.error(res.data.msg)
      refreshSimpleImage()
    }
  }).catch((err: any) => {
    ElMessage.error(err)
  })
}

const changeBehaviorImageType = (type: string) => {
  loading.value = true
  behaviorType.value = type
  captchaRef.value?.refresh()
}

const renderDataApi = async () => {
  const res = await axios.get(`${behaviorImageGenUrl}?type=${behaviorType.value}`)
  return res.data.captcha
}
const handleMatchingData = async (data: any) => {
  console.log('matching-data', data)
  const res = await axios.post(`${behaviorImageCheckUrl}`, data)
  matchingResultCode.value = res.data.code
}
const handleRenderSuccess = (success: boolean) => {
  console.log('render-success', success)
  loading.value = false
}
// 生命周期钩子
onMounted(() => {
  autofit.init({
    dh: 768,
    dw: 1024,
    el: "#app",
    resize: true,
  });
  simpleImageForm.timestamp = new Date().getTime().toString()
  changeSimpleImageType('spec')
})
</script>

<style>
#app {
  text-align: center;
  width: 50%;
  margin: 0 auto;
  user-select: none;
  -ms-user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
}

.el-form--inline {
  .el-form-item {
    .el-input, .el-cascader, .el-select, .el-autocomplete {
      width: 100px;
    }
  }
}
</style>
